<template>
 <div v-cloak>
   <template>
      <div class="align-right">
              <el-form :inline="true" :model="listQuery">
                  <div class="pull-right">
                    <el-form-item>
                        <el-input
                            placeholder="请输入机构名称"
                            clearable
                            v-model="listQuery.name">
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-input
                            placeholder="请输入机构编码"
                            clearable
                            v-model="listQuery.code">
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="handleSearch" icon="el-icon-search" >搜索</el-button>
                    </el-form-item>
                  </div>
                <div>
                 <el-button type="primary"  icon="plus" @click="handlerAdd">添加</el-button>
                </div>
              </el-form>
      </div>
      <tree-table  ref="treeTable"  :data="tableOrganizes"  :expandAll="expandAll" border> 
        <el-table-column align="left" label="机构编码" min-width ="100" >
              <template slot-scope="scope">
                  <span >{{ scope.row.code}}</span>
              </template>
        </el-table-column>
        <el-table-column align="center" label="机构状态" min-width ="100" >
              <template slot-scope="scope">
                  <span v-if="scope.row.enable == 1" style="color:green">
                    启用
                  </span>
                  <span v-else style="color:red">
                    禁用
                  </span>
              </template>
        </el-table-column>
        <el-table-column align="center" label="拥有角色" min-width="200px" >
              <template slot-scope="scope">
                  <span >{{ scope.row.roles}}</span>
              </template>
        </el-table-column>
        <el-table-column
              align="center"
              min-width="150px"
              label="操作"
              >
          <template slot-scope="scope">
          <div>
            <el-button type="text"  @click="handlerEdit(scope)" :disabled="scope.row.id == 1">修改</el-button>
            <el-button type="text" @click="handleDelete(scope)" :disabled="scope.row.id == 1">删除</el-button>
        </div>
          </template>
          </el-table-column>
      </tree-table>
  </template>
  <template>
    <el-dialog :title="textMap[dialogStatus]" :visible="dialogFormVisible" :before-close="cancel" center width="30%">
    <el-form :model="form" :rules="rules" ref="btnform" label-width="100px">
       <el-form-item label="父级节点" prop="parentCode">
          <menu-treeselect
            ref="selectTree"  
            :options="organizes"
            :normalizer="normalizer"
            :show-count="true"
            v-model="form.parentCode"
            placeholder="默认为根节点">
          </menu-treeselect>
      </el-form-item>
        <el-form-item label="机构名称" prop="name">
            <el-input v-model="form.name"   placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="机构编码" prop="code">
            <el-input v-model="form.code"   placeholder="请输入编码(例如:上级部门为100,直属下级为100.1)"></el-input>
        </el-form-item>
        <el-form-item label="机构状态" prop="enable">
            <el-radio-group v-model="form.enable" >
                    <el-radio class="radio" border :label="1">启用</el-radio>
                    <el-radio class="radio" border :label="0">禁用</el-radio>
            </el-radio-group>
        </el-form-item>
         <el-form-item label="角色配置" prop="roleIds" >
          <template>
            <div style="width:350px">
                <el-checkbox-group v-model="checkedBox">
                      <el-checkbox v-for="role in roles" :label="role.id" :key="role.id"  style="float:left;margin-left:5px">{{ role.name }}</el-checkbox>
                </el-checkbox-group>
             </div>
          </template>
        </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel()">取 消</el-button>
      <el-button v-if="dialogStatus=='create'" type="primary" @click="create('btnform')">确 定</el-button>
      <el-button v-else type="primary" @click="update('btnform')">确 定</el-button>
    </div>
  </el-dialog>
  </template>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
  // import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import treeTable from '@/components/TreeTable'
import { getOrganizingTree, getOrganizingRole, organizeInsert, organizeUpdate,organizeDel} from '@/api/sys/organize'
import { getAll} from '@/api/sys/role'
export default {
  components: { 
    treeTable,
    'menu-treeselect':Treeselect
  },
  data(){
    const validateCode = (rule, value, callback) => {
        if (value === null|| value === undefined || value === '') {
          callback(new Error('不能为空'));
        }else if(!this.ifCode(value,this.form.parentCode)){
          callback(new Error('编码格式不正确'));
        }else {
          callback();
        }
    }
    return {
        rules:{
          name:[{
            required: true,
            message:'名称不能为空',
            trigger: 'blur'
          }],
          code:[{
            required: true,
            validator: validateCode,
            trigger: 'blur'
          }]
        },
        checkedBox:[],
        roles: [],
        listQuery:{
          name: "",
          code: ""
        },
        form: {
            id: undefined,
            code: undefined,
            name: undefined,
            parentCode: undefined,
            enable: true,
            roleIds: []
        },
        dialogStatus:'',
        dialogFormVisible:false,
        textMap: {
            update: '编辑',
            create: '创建'
        },
        tableOrganizes:[],
        organizes:[],
        tempOrganizes:[],
        expandAll: true
    }   
  },
  created() {
    this.getList()
    this.getRoles()

  },
  methods: {
    getList() {
      getOrganizingTree(this.listQuery).then(response => {
          if (response.code === 0) {
            this.tableOrganizes = response.data
            this.tempOrganizes = JSON.parse(JSON.stringify(response.data))
          }
      })
    },
    getRoles(){
      getAll().then((response) => {
        if(response.code === 0) {
          this.roles = response.data
        }
      })
    },
    normalizer(node) {
      return {
        id: node.code,
        label: node.name,
        children: node.children
      }
    },
    handleSearch(){
      this.getList()
    },
    handlerAdd(){
       this.resetForm() 
       this.organizes = JSON.parse(JSON.stringify(this.tempOrganizes))
       const flag = this.$refs.treeTable.isSelected()
       if(flag){
            const node = this.$refs.treeTable.getSelectedNode()
            this.form.parentCode = node.code===""?undefined:node.code
       }       
       this.dialogStatus = 'create'
       this.dialogFormVisible = true
    },
    handlerEdit(scope){
      this.organizes =  JSON.parse(JSON.stringify(this.tempOrganizes)) 
      this.dialogStatus = 'update'
      this.dialogFormVisible = true 
      const row = scope.row
      const node = {
          id: row.id,
          code: row.code,
          name: row.name,
          parentCode: row.parentCode,
          enable: row.enable
      }
      this.recursionDisabled(this.organizes,node.code)
      this.form = node
      this.form.roleIds = []
      if(this.form.parentCode === ''){
          this.form.parentCode = undefined
      }
      this.$nextTick(function(){
        const currentNode = this.$refs.selectTree.getNode(node.code)
        currentNode.raw.isDisabled = true  
      })
      this.getRoles()
      const param = {"id":row.id}
      getOrganizingRole(param).then((response) => {
         this.checkedBox = response.data
      })
    },
    recursionDisabled(organizes,code){
      organizes.forEach((organize) => {
        const c = organize.code
        if(c === code){
          organize.isDisabled = true
        }
        if(organize.children){
          this.recursionDisabled(organize.children,code)
        }
       
      })
    },
    handlerConfig(scope){

    },
    handleDelete(scope){
      const row = scope.row
      const node = {
          id: row.id,
          code: row.code,
          name: row.name,
          parentCode: row.parentCode,
          enable: row.enable
      }
      organizeDel(node).then((response) => {
        if(response.code === 0){
          this.getList()
          this.$message({
            message: response.msg,
            type: 'success'
          })
        }
      })
    },
    create(formName){
       const set = this.$refs
       set[formName].validate(valid => {
          if(valid){
            this.form.roleIds = this.checkedBox
            const data = JSON.parse(JSON.stringify(this.form))
            if(data.parentCode === '' || data.parentCode === undefined){
              data.parentCode = ""
            }
            organizeInsert(data).then((response) =>{
              if(response.code === 0){
                this.getList()
                this.$message({
                  message: response.msg,
                  type: 'success'
                })
                this.cancel()
              }
            })
          }
       })
    },
    update(formName){
          const set = this.$refs
          set[formName].validate(valid => {
          if(valid){
            this.form.roleIds = this.checkedBox
            const data = JSON.parse(JSON.stringify(this.form))
            if(data.parentCode === undefined || data.parentCode === ""){
              data.parentCode = "";
            }
            organizeUpdate(data).then((response) =>{
              if(response.code === 0){
                this.getList()
                this.$message({
                  message: response.msg,
                  type: 'success'
                })
                this.cancel()
              }
            })
          }
       })
    },
    cancel(){
       this.dialogStatus = ''
       this.dialogFormVisible = false
       const set = this.$refs
       set['btnform'].clearValidate()
       this.resetForm()
       this.checkedBox = []
    },
    resetForm(){
        this.form = {
            id: undefined,
            id: undefined,
            code: undefined,
            name: undefined,
            parentCode: undefined,
            enable: 1,
            roleIds: []
        }
    },
    remote(row, callback) {
        callback(row.children)
    },
    ifCode(str,parentCode){
      const reg = /^[0-9]+$/
      if(parentCode != null && parentCode != ''){
        if(str.indexOf(parentCode+'.')!= -1){
          let  len1 = parentCode.length;
          let  len2 = str.length;
          str = str.substr(len1+1,len2-len1-1);
        }else {
          return false;
        }
      } 
      return reg.test(str)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.table-organize{
  margin: 10px
}
.table-search{
  margin: 10px;
  .el-input{
    width: 200px;
    margin-right: 6px;
  }
}
</style>